package me.sdevil507.org.po;


import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import me.sdevil507.supports.jpa.BaseJpaSnowflakeIdAndAuditEntity;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 机构部门表[OrgDeptPo]
 *
 * @author sdevil507
 * created on 2020-06-24 14:29:16
 */
@Entity
@Table(name = "biz_org_dept")
@Data
@EqualsAndHashCode(callSuper = true, exclude = {"org", "users"})
@ToString(exclude = {"org", "users"})
public class OrgDeptPo extends BaseJpaSnowflakeIdAndAuditEntity {

    /**
     * 部门名称
     */
    @Column
    private String title;

    /**
     * 部门编码
     */
    @Column
    private String code;

    /**
     * 机构父ID
     */
    @Column
    private Long parentId;

    /**
     * 同级排序
     */
    @Column
    private int sortNum;

    /**
     * 逻辑删除
     */
    @Column
    private boolean deleted = false;

    /**
     * 是否是智库
     */
    @Column
    private boolean itIsOrg;

    /**
     * 是否是智库根节点（第一级）
     */
    @Column
    private boolean itIsRoot;

    /**
     * 子机构
     */
    @OneToMany(cascade = CascadeType.REMOVE)
    @JoinColumn(name = "parentId", foreignKey = @ForeignKey(name = "none"))
    @OrderBy("sortNum ASC")
    @Where(clause = "deleted=0")
    private List<OrgDeptPo> children = new ArrayList<>(20);

    /**
     * 所属机构
     */
    @ManyToOne(fetch = FetchType.LAZY, cascade= CascadeType.ALL)
    @JoinColumn(name = "org_id", foreignKey = @ForeignKey(name = "none", value = ConstraintMode.NO_CONSTRAINT))
    private OrgPo org;

    /**
     * 包含用户
     */
    @ManyToMany(fetch = FetchType.LAZY, cascade= CascadeType.MERGE)
    @JoinTable(name = "biz_org_user_dept_rel",
            joinColumns = {
                    @JoinColumn(name = "dept_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "none"))},
            inverseJoinColumns = {
                    @JoinColumn(name = "user_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "none"))})
    @OrderBy("id ASC")
    private List<OrgUserPo> users;
}